import { reqUserLogin, reqUserLogout } from "@/api";

const state = {
  userInfo: {
    name: localStorage.getItem("name"),
    token: localStorage.getItem("token"),
  },
};
const actions = {
  async userLogin({ commit }, user) {
    const result = await reqUserLogin(user);
    if (result.code === 200) {
      localStorage.setItem("name", result.data.name);
      localStorage.setItem("token", result.data.token);
      commit("SAVE_USER_INFO", result.data);
    } else {
      alert("登入失败！");
      console.log(result.message);
    }
  },

  async userLogout({ commit }) {
    const result = await reqUserLogout();
    if (result.code === 200) {
      localStorage.removeItem("name");
      localStorage.removeItem("token");
      commit("REMOTE_USER_INFO");
    } else {
      console.log(result.message);
    }
  },
};
const mutations = {
  SAVE_USER_INFO(state, user) {
    state.userInfo.name = user.name;
    state.userInfo.password = user.token;
  },
  REMOTE_USER_INFO(state) {
    state.userInfo.name = "";
    state.userInfo.password = "";
  },
};
const getters = {};

export default {
  namespaced: true,
  state,
  actions,
  mutations,
  getters,
};
